package com.zx.idc.backend.gui.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zx.idc.backend.gui.api.ftp.BaseFtpOperatorFactory;
import com.zx.idc.backend.gui.api.ftp.FtpClientConfig;
import com.zx.idc.backend.gui.scheduler.sys.DataBackupJob;
import com.zx.idc.backend.gui.sys.service.ISysBackupLogJobService;
import com.zx.idc.common.exception.GlobalException;
import com.zx.idc.common.lang.SystemClock;
import com.zx.idc.common.util.JsonUtil;
import com.zx.idc.ds.common.service.impl.BaseServiceImpl;
import com.zx.idc.ds.sys.bean.DataBackupSetting;
import com.zx.idc.ds.sys.bean.OffSiteBackupSetting;
import com.zx.idc.ds.sys.dao.SysBackupLogMapper;
import com.zx.idc.ds.sys.entity.SysBackupLog;
import com.zx.idc.ds.sys.entity.SysConfiguration;
import com.zx.idc.ds.sys.service.ISysConfigurationService;
import com.zx.idc.qc.core.QuartzTaskService;
import com.zx.idc.qc.entity.TaskEntity;
import com.zx.idc.qc.exception.JobExistsException;
import com.zx.idc.qc.exception.QuartzJobException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author rxliuli
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ISysBackupLogJobServiceImpl extends BaseServiceImpl<SysBackupLogMapper, SysBackupLog> implements ISysBackupLogJobService {
    @Autowired
    private ISysConfigurationService sysConfigurationService;
    @Autowired
    private QuartzTaskService quartzTaskService;

    @Override
    public Boolean updateSettings(DataBackupSetting dataBackupSetting, OffSiteBackupSetting offSiteBackupSetting, Integer userId) {
        final boolean result = sysConfigurationService.update(new SysConfiguration().setConfigValue(JsonUtil.write(dataBackupSetting)), new EntityWrapper<>(new SysConfiguration().setConfigKey(DataBackupSetting.DATA_BACKUP_SETTING_CONFIG_KEY)))
            && sysConfigurationService.update(new SysConfiguration().setConfigValue(JsonUtil.write(offSiteBackupSetting)), new EntityWrapper<>(new SysConfiguration().setConfigKey(OffSiteBackupSetting.OFF_SITE_BACKUP_SETTING_CONFIG_KEY)));
        if (!result) {
            throw new GlobalException("更新自动备份设置失败");
        }
        final Map<String, Object> map = new HashMap<>(1);
        map.put("userId", userId);
        map.put("backupIcpPicture", dataBackupSetting.getBackupIcpPicture());
        map.put("backupIcpIspFile", dataBackupSetting.getBackupIcpIspFile());
        TaskEntity taskEntity = new TaskEntity()
            .setJobClass(DataBackupJob.class.getName())
            // 按照固定天数周期性地调用
            .setCronExpression("0 0 0 1/" + dataBackupSetting.getBackupIcpDay() + " * ? ")
            .setJobGroup("backend")
            .setJobName("backend " + userId)
            .setStartTime(SystemClock.now())
            .setJobDataMap(map)
            .setJobDescription("数据备份 job");
        try {
            if (dataBackupSetting.getBackupIcpDay() == 0) {
                quartzTaskService.deleteTask(taskEntity);
                return true;
            }
            quartzTaskService.deleteTask(taskEntity);
            return quartzTaskService.addCronTask(taskEntity);
        } catch (QuartzJobException e) {
            log.error("数据备份 job 创建失败", e);
        } catch (JobExistsException e) {
            log.error("数据备份 job 任务已存在", e);
        } catch (ParseException e) {
            log.error("cron 表达式格式错误", e);
        }
        return false;
    }
}
